package com.yunying.rispro.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yunying.rispro.exception.BusinessException;
import com.yunying.rispro.model.Doctor;
import com.yunying.rispro.service.IDoctorService;
import com.yunying.rispro.util.JsonResponseStatus;
import com.yunying.rispro.vo.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截处理类
 */
@Component
@Slf4j  //日志
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IDoctorService doctorService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在执行controller方法(handler)之前进行执行
        /**
         * 1.需要判断请求的接口路径是否为HandlerMethod（controller方法）
         * 2.判断token是否为空，如果为空 未登录
         * 3.token不为空，登录验证 loginService checkToken
         * 4.如果认证成功，放行
         */
        if(!(handler instanceof HandlerMethod)){
            //有可能是资源handler 如RequestResourceHandler，访问静态资源，直接放行
            return true;
        }
        //String token = request.getHeader("Authorization"); //获取浏览器头部token
        String token1 = request.getHeader("Cookie"); //获取浏览器头部token
        String token = token1.substring(6);

        //打印日志
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if(StringUtils.isBlank(token)){ //检查token是否为空
            BusinessException exception = new BusinessException(JsonResponseStatus.LOGIN_NULL);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(exception); //未登录,传给前端信息
            return false;
        }

        Doctor doctor = doctorService.checkToken(token);
        if(doctor == null){  //检查token是否有用户信息
            BusinessException exception = new BusinessException(JsonResponseStatus.LOGIN_NULL);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(exception); //未登录,传给前端信息
            return false;
        }
        //登录成功，放行，并将用户信息保存在 本地用户类（后面有介绍）
        UserThreadLocal.put(doctor); //放入本地local
        return true;
    }

    @Override  //所以的方法都执行完之后，收尾工作
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删除 ThreadLocal中用完的信息，会有内存泄露的风险
        UserThreadLocal.remove();
    }
}
